﻿package com.agileai.miscdp.hotweb.generator.treemanage;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;

import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.database.DBManager;
import com.agileai.miscdp.hotweb.database.SqlBuilder;
import com.agileai.miscdp.hotweb.domain.Column;
import com.agileai.miscdp.hotweb.domain.treemanage.TreeManageFuncModel;
import com.agileai.miscdp.hotweb.domain.treemanage.TreeManageTableModel;
import com.agileai.miscdp.hotweb.generator.Generator;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
/**
 * SQLMap文件代码生成器
 */
public class TMMSqlMapGenerator implements Generator{
	private String tableName = null;
	private String sqlMapFile = null;
    private String templateDir = null;
    private TreeManageFuncModel funcModel = null;
    
	public void init(TreeManageTableModel treeMangeTableModel){
    	try {
			String tableName = treeMangeTableModel.getTableName();
			String nameSpace = MiscdpUtil.getValidName(tableName);
			treeMangeTableModel.setNamespace(nameSpace);
			treeMangeTableModel.setSchema(tableName);
			
			SqlBuilder sqlBuilder = new SqlBuilder();
			String deleteTreeRecordSql = sqlBuilder.deleteSql(tableName, funcModel.getIdField());
			treeMangeTableModel.setDeleteTreeRecordSql(deleteTreeRecordSql);
			
			String queryMaxSortIdSql = sqlBuilder.queryMaxSortIdSql(tableName, funcModel.getSortField(), funcModel.getParentIdField());
			treeMangeTableModel.setQueryMaxSortIdSql(queryMaxSortIdSql);
			
			String projectName = funcModel.getProjectName();
			DBManager dbManager = DBManager.getInstance(projectName);
			String[] colNames = MiscdpUtil.getColNames(dbManager, tableName);
			
			HashMap<String, Column> columnMap = dbManager.getColumnMap(tableName);
			sqlBuilder.addColumnsMap(tableName,columnMap);
			
            String listSql = sqlBuilder.findAllSql(tableName,colNames);
            String queryTreeRecordsSql = listSql + " order by "+ funcModel.getParentIdField()+","+funcModel.getSortField();
            treeMangeTableModel.setQueryTreeRecordsSql(queryTreeRecordsSql);
            
            String[] primaryKeys = dbManager.getPrimaryKeys(tableName);
			List<String> paramFieldList = new ArrayList<String>();
			paramFieldList.add(funcModel.getIdField());
			String uniqueFieldCode = funcModel.retrieveUniqueField(funcModel.getPageFormFields());
			if (StringUtil.isNotNullNotEmpty(uniqueFieldCode)){
				paramFieldList.add(uniqueFieldCode);
			}
			String[] paramFields = paramFieldList.toArray(new String[0]);
			String queryTreeRecordSql = sqlBuilder.retrieveSqlByParams(colNames,tableName,paramFields);
            treeMangeTableModel.setQueryTreeRecordSql(queryTreeRecordSql);
            
            String updateTreeRecordSql = sqlBuilder.updateSql(tableName, colNames, primaryKeys);
            treeMangeTableModel.setUpdateTreeRecordSql(updateTreeRecordSql);

            String insertTreeRecordSql = sqlBuilder.insertSql(tableName, colNames, "CHILD_");
            treeMangeTableModel.setInsertTreeRecordSql(insertTreeRecordSql);
            
            String queryCurLevelRecordsSql = sqlBuilder.queryCurLevelRecordsSql(tableName, colNames
            		, funcModel.getIdField(), funcModel.getParentIdField(), funcModel.getSortField());
			treeMangeTableModel.setQueryCurLevelRecordsSql(queryCurLevelRecordsSql);
			
			String queryChildRecordsSql = listSql + " where "+ funcModel.getParentIdField() + " = #value#"
			+ " order by "+funcModel.getSortField();
			treeMangeTableModel.setQueryChildRecordsSql(queryChildRecordsSql);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void generate() {
		try {
			String fileName = "template";
			try {
				templateDir = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource(fileName)).getFile().toString();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			Configuration cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(templateDir+"/treemanage"));
	        cfg.setObjectWrapper(new DefaultObjectWrapper());
	        Template temp = cfg.getTemplate("SqlMap.xml.ftl");
	        TreeManageTableModel standardTableModel = new TreeManageTableModel();
	        standardTableModel.setTableName(tableName);
	        this.init(standardTableModel);
	        Map root = new HashMap();
	        root.put("table",standardTableModel);
	        FileWriter out = new FileWriter(new File(this.sqlMapFile));
//	        Writer out = new OutputStreamWriter(System.out);
	        temp.process(root, out);
	        out.flush();			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public void setSqlMapFile(String sqlMapFile) {
		this.sqlMapFile = sqlMapFile;
	}

	public void setFuncModel(TreeManageFuncModel funcModel) {
		this.funcModel = funcModel;
	}
}
